import paho.mqtt.client as mqtt
from application import settings
import json
import time
import uuid

# 没改完
class MqttClient:
    def __init__(self, client_id,username,password):
        # 初始化 MQTT 客户端
        self._client = mqtt.Client(client_id=settings.CLIENT_ID)
        self._client.username_pw_set(username=username, password=password)
        # 指定回调函数
        self._client.on_connect = self.on_connect
        self._client.on_message = self.on_message

    def on_connect(self, client, userdata, flags, rc):
        print('Connected with result code ' + str(rc))
        client.subscribe('testtopic/#')

    def on_message(self, client, userdata, msg):
        print(msg.topic + " " + str(msg.payload))

    def connect(self, host='192.168.10.8', port=8810, keepalive=60):
        # 建立连接
        self._client.connect(host, port, keepalive)

    def publish(self, topic, payload, qos=0):
        # 发布消息
        self._client.publish(topic, payload, qos)

    def loop_forever(self):
        # 运行 MQTT 客户端循环
        self._client.loop_start()  # 注意这里改为 loop_start，因为可能需要在其他线程运行

# 使用示例
# if __name__ == "__main__":
#     client1 = MqttClient()
#     client1.connect()
#     client1.loop_forever()

#     client2 = MqttClient()
#     client2.connect('192.168.10.9', 1883)  # 可以连接到不同的服务器和端口
#     client2.loop_forever()